﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Resources;
using System.Xml.Linq;
using Lib.Helper;
using MSIACCSL2.ViewModels;
using MSIACCSL2.Views.Login;
using MSIACCSL2.Views.User;
using MapulRibbon;
using WcfService1.DTO;


namespace MSIACCSL2
{
    public partial class MasterPage : Page
    {
        public MainViewModel VM
        {
            get { return this.DataContext as MainViewModel; }
        }
     
        public MasterPage()
        {
            InitializeComponent();

            EventAggregator.RegisterMessage("LoginSukes", (x,y) =>
                                                             {
                                                                 VM.GetMenus((UserDTO)x);
                                                                 Navigation.MyNavigation.Navigate(new Uri("/Home",UriKind.Relative));
                                                             });

            
            MainViewModel.OnLoadCompleted = (x) =>
            {
                this.DataContext = (MainViewModel)x;
                mainRibbon.Tabs.Items.Clear();
                var tabs = new Tabs();
                foreach (var menu in VM.Menus.Where(m => m.ParentMenu == null))
                {

                    var tab1 = new TabsItem();
                    tab1.Header = menu.MenuText;

                    BuildSubMenuNew(menu, tab1);
                    mainRibbon.Tabs.Items.Add(tab1);
                }
               
            };

            ContentFrame.Navigating += ContentFrame_Navigating;
            ContentFrame.Navigated += ContentFrame_Navigated;
            ContentFrame.NavigationFailed += ContentFrame_NavigationFailed;
            ContentFrame.NavigationStopped += ContentFrame_NavigationStopped;
            SizeChanged += MasterPage_SizeChanged;
            this.Loaded += MasterPage_Loaded;
        }

        void ContentFrame_NavigationStopped(object sender, NavigationEventArgs e)
        {
            VM.IsBusy = false;
        }

        void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            VM.IsBusy = false;
        }

        void MasterPage_Loaded(object sender, RoutedEventArgs e)
        {
            mainRibbon.Tabs.Items.Clear();
        }

       
        void MasterPage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            LayoutRoot.Width = e.NewSize.Width;
            LayoutRoot.Height = e.NewSize.Height;
        }

        void ContentFrame_Navigated(object sender, NavigationEventArgs e)
        {
            if (e.Content is Page)
            {
                if (GlobalVar.User == null && e.Content.ToString() != "MSIACCSL2.Views.Login.FrmLogin")
                {
                    ((Page)e.Content).NavigationService.Navigate(new Uri("/Login/FrmLogin", UriKind.Relative));
                }
            
            }
                
            VM.IsBusy = false;
        }

        void ContentFrame_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            VM.IsBusy = true;
        }

        private void BuildSubMenuNew(MenuDTO parent, TabsItem parentMenu)
        {
           
            if (parent.SubMenus != null)
            {
                var ribbonItems = new RibbonItems();
                var ribbonItem = new RibbonItem();
                var rbGroups = new RibbonButtonsGroup();
                rbGroups.Orientation = Orientation.Horizontal;
                rbGroups.HasBorder = true;

                foreach (MenuDTO menu in parent.SubMenus)
                {
                    var rb1 = new RibbonButton();
                    rb1.Text = menu.MenuText;
                    rb1.Height = 25;
                    rb1.Width = 100;
                    string url = string.Empty;
                    url = menu.URL;
                    rb1.OnClick += (o, e) =>
                    {
                        if (url.Contains("aspx"))
                        {
                            var button = new MyButton(GlobalVar.ReportUrl + url);
                            button.ClickMe();
                        }
                        else if (url.Contains("xap"))
                        {
                            var wc = new WebClient();
                            wc.OpenReadCompleted += wc_OpenReadCompleted;
                            wc.OpenReadAsync(new Uri(GlobalVar.ReportUrl.Replace("ReportPage", "ClientBin") + url, UriKind.RelativeOrAbsolute), url.Replace(".xap", ""));
                        }
                        else
                            Navigation.MyNavigation.Navigate(new Uri(url, UriKind.Relative));
                    };

                    var border1 = new Border();
                    border1.BorderThickness = new Thickness(1, 1, 1, 1);
                    border1.BorderBrush = new SolidColorBrush(Color.FromArgb(100, 183, 185, 88));
                    border1.Child = rb1;
                    border1.Margin = new Thickness(1);
                    rbGroups.Children.Add(border1);
                }
              
                ribbonItem.Content = rbGroups;
                ribbonItems.Children.Add(ribbonItem);
                parentMenu.Content = ribbonItems;
               
            }
                

          
        }

        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            StreamResourceInfo sri = new StreamResourceInfo(e.Result, "application/binary");

            Stream manifestStream = Application.GetResourceStream(sri, new Uri("AppManifest.xaml", UriKind.Relative)).Stream;
            string appManifest = new StreamReader(manifestStream).ReadToEnd();

            XElement deploymentRoot = XDocument.Parse(appManifest).Root;
            List<XElement> deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts)
                                              .ToList();

            Assembly asm = null;

            foreach (XElement xElement in deploymentParts)
            {
                string source = xElement.Attribute("Source").Value;
                AssemblyPart asmPart = new AssemblyPart();

                StreamResourceInfo streamInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, "application/binary"), new Uri(source, UriKind.Relative));
                if (source == e.UserState.ToString() + ".dll")
                {
                    asm = asmPart.Load(streamInfo.Stream);
                    break;
                }
            }
            var page = asm.CreateInstance("JurnalUmum.Views.Jurnal.Index");
            EventAggregator.PublishMessage("LoadPageFromFile", page);
        }

        private void AboutTemplate_MouseLeave(object sender, MouseEventArgs e)
        {
            mainRibbon.RibbonAboutTemplate.Hide();
        }

        private void mainRibbon_OnSelectionTabChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            //((sender as TabControl).SelectedItem as TabItem);
        }

        private void SomeRibbonObject_OnClick(object sender, EventArgs e)
        {
            if (sender is RibbonButtonBase)
                MessageBox.Show("You are clicked: " + (sender as RibbonButtonBase).Name);
            else if (sender is RibbonListItem)
                MessageBox.Show("You are clicked item: " + (sender as RibbonListItem).Name);
        }

        private void undoButton_OnClick(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Navigation.MyNavigation.CanGoBack)
                Navigation.MyNavigation.GoBack();
        }

        private void redoButton_OnClick(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Navigation.MyNavigation.CanGoForward)
                Navigation.MyNavigation.GoForward();
        }
      
    }
}
